package com.oceansoft.core.jxkh.dao.impl;

import com.oceansoft.core.jxkh.dao.ImageInDBDao;
import com.oceansoft.core.jxkh.domain.Photo;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by OS on 2017/12/7.
 */


@Repository
public class ImageInDBImpl implements ImageInDBDao{

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void ImageIn(String path) {
        final String p = path;
        final String[] imageNames = getFileName(path);
        String sql = "insert into t_sys_user_photo(dbid,name,photo) values(seq_sys_user_photo.NEXTVAL,?,?)";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setString(1,imageNames[i]);
                ps.setString(2,GetImageStr(p+"/"+imageNames[i]));
            }

            @Override
            public int getBatchSize() {
                return imageNames.length;
            }
        });

    }

    @Override
    public List<Photo> ImageOut() {
        String sql = "select name,photo from t_sys_user_photo";
        List<Photo> list = jdbcTemplate.query(sql, new RowMapper<Photo>() {
            @Override
            public Photo mapRow(ResultSet rs, int args) throws SQLException {
                Photo photo = new Photo();
                photo.setName(rs.getString("name"));
                photo.setPhoto(rs.getString("photo"));
                return photo;
            }
        });
        return list;
    }

    public static String [] getFileName(String path)
    {
        File file = new File(path);
        String [] fileName = file.list();
        return fileName;
    }

    public static String GetImageStr(String imgFile) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        System.out.println(imgFile);
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }
}
